// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.PositionFlow1;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.PositionFlow1Mapper;
import com.fowo.api.mapper.ProductMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.WarehouseBinMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.position.flow1.PositionFlow1ExcelPo;
import com.fowo.api.model.position.flow1.PositionFlow1ImportPo;
import com.fowo.api.model.position.flow1.PositionFlow1ItemVo;
import com.fowo.api.model.position.flow1.PositionFlow1SearchParamPo;
import com.fowo.api.model.position.flow1.PositionFlow1Vo;
import com.fowo.api.model.product.ProductItemVo;
import com.fowo.api.model.product.ProductSearchParamPo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.model.warehouse.bin.WarehouseBinItemVo;
import com.fowo.api.model.warehouse.bin.WarehouseBinSearchParamPo;
import com.fowo.api.service.PositionFlow1Service;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 仓位流水1 服务实现类
 * @author 蜂窝蜜造平台 配置人：吴天洋，彭增辉
 */
@Service
@Slf4j
@DataObjectType(PositionFlow1.class)
@DS("ds24")
public class PositionFlow1ServiceImpl
  extends ServiceImpl<PositionFlow1Mapper, PositionFlow1>
  implements PositionFlow1Service {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("itemIdName", "p.`name`");
      put("shopIdShopName", "si.`shop_name`");
      put("stockIdName", "w.`name`");
      put("binIdStorageBin", "wb.`storage_bin`");
      put("wareattributeName", "w2.`name`");
      put("wareattributeType", "w2.`type`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected PositionFlow1Service self;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected ProductMapper productMapper;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected WarehouseBinMapper warehouseBinMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  protected Validator validator;

  /**
   * 创建仓位流水1
   * @param model 仓位流水1
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(PositionFlow1Vo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    PositionFlow1 entity = new PositionFlow1();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("仓位流水1保存失败");
  }

  /**
   * 更新仓位流水1
   * @param model 仓位流水1
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(PositionFlow1Vo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    PositionFlow1 entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("仓位流水1不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "lastUpdateTime",
      "lastUpdateUser",
      "id",
      "createUser",
      "createTime"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新仓位流水1（带空值）
   * @param model 仓位流水1
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(PositionFlow1Vo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    PositionFlow1 entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("仓位流水1不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(PositionFlow1::getOperateTime, model.getOperateTime())
      .set(PositionFlow1::getType, model.getType())
      .set(PositionFlow1::getCountnum, model.getCountnum())
      .set(PositionFlow1::getItemId, model.getItemId())
      .set(PositionFlow1::getFormNum, model.getFormNum())
      .set(PositionFlow1::getLastUpdateTime, model.getLastUpdateTime())
      .set(PositionFlow1::getLastUpdateUser, model.getLastUpdateUser())
      .set(PositionFlow1::getSku, model.getSku())
      .set(PositionFlow1::getFnSku, model.getFnSku())
      .set(PositionFlow1::getShopId, model.getShopId())
      .set(PositionFlow1::getStockId, model.getStockId())
      .set(PositionFlow1::getBinId, model.getBinId())
      .set(PositionFlow1::getLockQty, model.getLockQty())
      .set(PositionFlow1::getWayQty, model.getWayQty())
      .set(PositionFlow1::getStockQty, model.getStockQty())
      .set(PositionFlow1::getFormOperator, model.getFormOperator())
      .set(PositionFlow1::getWareattribute, model.getWareattribute())
      .set(PositionFlow1::getReamark, model.getReamark())
      .eq(PositionFlow1::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(PositionFlow1SearchParamPo search) {
    return false;
  }

  /**
   * 删除仓位流水1
   * @param id 仓位流水1的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除仓位流水1
   * @param ids 仓位流水1的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<PositionFlow1ImportPo> excelToImportRow(
    PositionFlow1ImportPo row,
    Integer rowNumber,
    PositionFlow1Vo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<PositionFlow1ImportPo> ir =
      new ImportRow<PositionFlow1ImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<PositionFlow1ImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new PositionFlow1Vo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, PositionFlow1ImportPo.class);

    // 一般数据处理
    vo.setProductionDate(SheetUtils.tryToDate(row.getProductionDate()));
    SheetUtils.datePreviewFormat(
      row.getProductionDate(),
      row::setProductionDate
    );
    vo.setOperateTime(SheetUtils.tryToDate(row.getOperateTime()));
    SheetUtils.datePreviewFormat(row.getOperateTime(), row::setOperateTime);
    if (StringUtils.hasText(row.getType())) {
      List<SysDictAllItem> typeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "type",
          n -> sysDictService.getDictItems("SCM00070")
        );
      PositionFlow1Vo finalVo = vo;
      typeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setType(i.getItemValue()),
          () ->
            ir.addError(
              "type",
              String.format(
                "必须为 %s 中之一",
                typeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setLockQty(SheetUtils.tryToDecimal(row.getLockQty()));
    vo.setWayQty(SheetUtils.tryToDecimal(row.getWayQty()));
    vo.setStockQty(SheetUtils.tryToDecimal(row.getStockQty()));
    vo.setProjectId(SheetUtils.tryToLong(row.getProjectId()));
    vo.setShelfLife(SheetUtils.tryToLong(row.getShelfLife()));
    vo.setExpiryDate(SheetUtils.tryToDate(row.getExpiryDate()));
    SheetUtils.datePreviewFormat(row.getExpiryDate(), row::setExpiryDate);
    vo.setChangeWayQty(SheetUtils.tryToDecimal(row.getChangeWayQty()));
    vo.setChangeStockQty(SheetUtils.tryToDecimal(row.getChangeStockQty()));
    vo.setChangeLockQty(SheetUtils.tryToDecimal(row.getChangeLockQty()));
    // 处理关联字段“品名”
    if (
      !SheetUtils.isBlank(row.getItemIdName()) &&
      SheetUtils.isBlank(row.getItemId())
    ) {
      ProductSearchParamPo itemIdSearchParam = new ProductSearchParamPo();
      itemIdSearchParam.setLimit(2); // 最大只返回二行记录
      itemIdSearchParam.setNameEq(SheetUtils.trim(row.getItemIdName()));
      itemIdSearchParam.applySqlSegments();
      List<ProductItemVo> itemIdMatches = productMapper.search(
        itemIdSearchParam
      );
      if (itemIdMatches.size() == 0) {
        ir.addError("itemIdName", "未能在产品管理中找到匹配的数据");
      } else if (itemIdMatches.size() > 1) {
        ir.addError("itemIdName", "关联不唯一，在产品管理中找到多个匹配的数据");
      } else {
        vo.setItemId(itemIdMatches.get(0).getId());
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", itemIdMatches.get(0).getId())
          .put("fromObjectName", "PositionFlow1")
          .put("fromObjectId", vo.getId())
          .put("fromField", "itemId")
          .build();

        final List<JoinModel> joinModels = new ArrayList<>(1);
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains(null)
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("sku")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName(null)
              .rowFieldName(null)
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        SheetUtils.joinHandle(
          null,
          ir,
          null,
          vo,
          CollUtil.getFirst(itemIdMatches),
          joinModels
        );
      }
    }
    // 处理关联字段“店铺”
    if (
      !SheetUtils.isBlank(row.getShopIdShopName()) &&
      SheetUtils.isBlank(row.getShopId())
    ) {
      ShopInfoSearchParamPo shopIdSearchParam = new ShopInfoSearchParamPo();
      shopIdSearchParam.setLimit(2); // 最大只返回二行记录
      shopIdSearchParam.setShopNameEq(SheetUtils.trim(row.getShopIdShopName()));
      shopIdSearchParam.applySqlSegments();
      List<ShopInfoItemVo> shopIdMatches = shopInfoMapper.search(
        shopIdSearchParam
      );
      if (shopIdMatches.size() == 0) {
        ir.addError("shopIdShopName", "未能在店铺中找到匹配的数据");
      } else if (shopIdMatches.size() > 1) {
        ir.addError("shopIdShopName", "关联不唯一，在店铺中找到多个匹配的数据");
      } else {
        vo.setShopId(shopIdMatches.get(0).getId());
      }
    }
    // 处理关联字段“仓库”
    if (
      !SheetUtils.isBlank(row.getStockIdName()) &&
      SheetUtils.isBlank(row.getStockId())
    ) {
      WarehouseSearchParamPo stockIdSearchParam = new WarehouseSearchParamPo();
      stockIdSearchParam.setLimit(2); // 最大只返回二行记录
      stockIdSearchParam.setNameEq(SheetUtils.trim(row.getStockIdName()));
      stockIdSearchParam.applySqlSegments();
      List<WarehouseItemVo> stockIdMatches = warehouseMapper.search(
        stockIdSearchParam
      );
      if (stockIdMatches.size() == 0) {
        ir.addError("stockIdName", "未能在仓库即时库存中找到匹配的数据");
      } else if (stockIdMatches.size() > 1) {
        ir.addError(
          "stockIdName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setStockId(stockIdMatches.get(0).getId());
      }
    }
    // 处理关联字段“仓位”
    if (
      !SheetUtils.isBlank(row.getBinIdStorageBin()) &&
      SheetUtils.isBlank(row.getBinId())
    ) {
      WarehouseBinSearchParamPo binIdSearchParam =
        new WarehouseBinSearchParamPo();
      binIdSearchParam.setLimit(2); // 最大只返回二行记录
      binIdSearchParam.setStorageBinEq(
        SheetUtils.trim(row.getBinIdStorageBin())
      );
      binIdSearchParam.applySqlSegments();
      List<WarehouseBinItemVo> binIdMatches = warehouseBinMapper.search(
        binIdSearchParam
      );
      if (binIdMatches.size() == 0) {
        ir.addError("binIdStorageBin", "未能在仓位中找到匹配的数据");
      } else if (binIdMatches.size() > 1) {
        ir.addError(
          "binIdStorageBin",
          "关联不唯一，在仓位中找到多个匹配的数据"
        );
      } else {
        vo.setBinId(binIdMatches.get(0).getId());
      }
    }
    // 处理关联字段“仓库属性”
    if (
      !SheetUtils.isBlank(row.getWareattributeName()) &&
      SheetUtils.isBlank(row.getWareattribute())
    ) {
      WarehouseSearchParamPo wareattributeSearchParam =
        new WarehouseSearchParamPo();
      wareattributeSearchParam.setLimit(2); // 最大只返回二行记录
      wareattributeSearchParam.setNameEq(
        SheetUtils.trim(row.getWareattributeName())
      );
      wareattributeSearchParam.applySqlSegments();
      List<WarehouseItemVo> wareattributeMatches = warehouseMapper.search(
        wareattributeSearchParam
      );
      if (wareattributeMatches.size() == 0) {
        ir.addError("wareattributeName", "未能在仓库即时库存中找到匹配的数据");
      } else if (wareattributeMatches.size() > 1) {
        ir.addError(
          "wareattributeName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setWareattribute(wareattributeMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<PositionFlow1ImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<PositionFlow1ImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            PositionFlow1ImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              PositionFlow1ImportPo row,
              AnalysisContext cxt
            ) {
              PositionFlow1Vo vo = new PositionFlow1Vo();
              ImportRow<PositionFlow1ImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<PositionFlow1ImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<PositionFlow1ImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      PositionFlow1Vo vo = new PositionFlow1Vo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    PositionFlow1SearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "operateTime",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "type",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00070")
      );
      exportOptions.addFieldMappingOption(
        "itemId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((PositionFlow1ItemVo) r).getItemIdName())
          )
      );
      exportOptions.addFieldMappingOption(
        "shopId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((PositionFlow1ItemVo) r).getShopIdShopName())
          )
      );
      exportOptions.addFieldMappingOption(
        "stockId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((PositionFlow1ItemVo) r).getStockIdName())
          )
      );
      exportOptions.addFieldMappingOption(
        "binId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((PositionFlow1ItemVo) r).getBinIdStorageBin())
          )
      );
      exportOptions.addFieldMappingOption(
        "wareattribute",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((PositionFlow1ItemVo) r).getWareattributeName())
          )
      );
      exportOptions.addStringFields(
        "type",
        "countnum",
        "itemIdName",
        "formNum",
        "sku",
        "fnSku",
        "shopIdShopName",
        "stockIdName",
        "binIdStorageBin",
        "formOperator",
        "wareattributeName",
        "wareattributeType",
        "reamark"
      );

      String fileName = String.format(
        "仓位流水1(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> typeItems = sysDictService.getDictItems("SCM00070");
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<PositionFlow1ExcelPo> items = new ArrayList<PositionFlow1ExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<PositionFlow1ItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<PositionFlow1ItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (PositionFlow1ItemVo item : list) {
        PositionFlow1ExcelPo excel = new PositionFlow1ExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getType() != null) {
          typeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getType()))
            .findFirst()
            .ifPresent(i -> excel.setType(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "仓位流水1(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(PositionFlow1ExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过单据号查询仓位流水1主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByCountnum(String countnum) {
    return this.baseMapper.getIdByCountnum(countnum);
  }

  /**
   * 通过单据号查询仓位流水1多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByCountnum(List<String> list) {
    return this.baseMapper.getIdsByCountnum(list);
  }

  /**
   * 通过仓位流水1主键查询单据号
   */
  @Override
  public String getCountnumById(Long id) {
    return this.baseMapper.getCountnumById(id);
  }

  /**
   * 通过仓位流水1主键查询单据号列表
   */
  @Override
  public List<String> getCountnumByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getCountnumByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("countnum"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 仓位流水1的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public PositionFlow1Vo getVoById(Long id) throws Exception {
    PositionFlow1Vo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询仓位流水1
   * @param search 查询条件
   * @return 仓位流水1分页查询结果
   */
  @Override
  public Page<PositionFlow1ItemVo> pageSearch(
    PositionFlow1SearchParamPo search
  ) {
    Page<PositionFlow1ItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(PositionFlow1ItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 仓位流水1快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'PositionFlow1Options::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<PositionFlow1ItemVo>> searchOptions(
    PositionFlow1SearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询仓位流水1
   * @param search 查询条件
   * @return 仓位流水1列表查询结果
   */
  @Override
  public List<PositionFlow1ItemVo> search(PositionFlow1SearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询仓位流水1最后更新时间
   * @param search 查询条件
   * @return 仓位流水1最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(PositionFlow1SearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }
}
